﻿//=============================================================
// Copyright (C) 2011 深圳市中旭企业管理股份有限公司
// 作 者：江怀玉
// 日 期：2011-10-11
// 描 述: 用于生成数据结果的JSON数据格式
// URL parameter:
//        entity:当前实体对象名称(不一定是表名)
//        codition:过滤数据条件
//        pageindex:当前页
//        pagesize:页记录数
//        type:JSON的数据类型，有时候用于List.aspx使用，有时用于生成对应的JS Obecjt Entity!
//        order:排序
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00   2011/10/11   江怀玉    
// 1.01   2011/11/21   江怀玉            增加获取数据权限功能
// 1.02   2011/11/23   江怀玉            增加获取自定义查询条件功能
//
//=============================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Common;
using ZX.BLL;
using ZX.DBModule;
using System.Text.RegularExpressions;
using System.Text;


using ZX.Web.UI.Controls;
using ZX.BLL.Extend;

namespace ZX.WebApp.AjaxData
{
    public partial class JSObject : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string strEntity = this.GetStringFromQueryString("entity", "E_Menu");            //对应的实体
            string strCondition = this.GetStringFromQueryString("condition", "");            //系统特定条件
            string strCustomCondition = this.GetStringFromQueryString("customCondition", "");//自定义条件
            int iPageIndex = this.GetIntFromQueryString("pageindex", 0);                     //第N页？
            int iPageSize = this.GetIntFromQueryString("pagesize", 0);                       //页记录数？
            string IsOnlyTotal = this.GetStringFromQueryString("onlyTotal","false");         //是否只回传记录总数?
            string IsDesc = this.GetStringFromQueryString("desc", "false");                  //Yes or No
            // strCondition = Server.UrlDecode(strCondition);
            // strCustomCondition = Server.UrlDecode(strCustomCondition);
            // 系统数据权限
            strCondition = strCondition == "" ? getRoleCondition() : strCondition + (getRoleCondition() == "" ? "" : " and "+getRoleCondition());
            strCondition = strCondition == "" ? strCustomCondition : strCondition + (strCustomCondition == "" ? "" : " and " + strCustomCondition);
            
            
            string strType = this.GetStringFromQueryString("type", "");
            string strOrder = this.GetStringFromQueryString("order", "");
            strEntity= strEntity.Split(',')[0];
       
            BaseEntity entity = ZX.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;

            if (strType == "1")
            {
                HttpContext.Current.Response.Write(entity.ToJSON());
                return;
            }
            


            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            bll.PageIndex = iPageIndex;
            bll.PageSize = iPageSize==0?25:iPageSize;
            bll.Order = strOrder;
            bll.Desc = "Yes";
            IList<BaseEntity> list;
            
            int totalrecord = bll.GetRowCount(strCondition);
            if (IsOnlyTotal == "true")
            {
                Response.Write("var " + strEntity + "_ResCount=[{\"total\":" + totalrecord.ToString() + "}];");
                return;
            }
            if (bll.PageIndex == 0)
            {
                list = string.IsNullOrEmpty(strCondition) ? bll.GetEntitysByCondition("1=1") : bll.GetEntitysByCondition(strCondition);
            }
            else
            {
                list = string.IsNullOrEmpty(strCondition) ? bll.GetEntitysSplitPage("1=1") : bll.GetEntitysSplitPage(strCondition);
            }
            if (list==null)
            {
                HttpContext.Current.Response.Write("[{\"N\":\"null\"}]");
                return;
            }
            //int totalrecord = bll.GetRowCount(strCondition);
            string strFormat = "var "+strEntity+"Res={\"total\":" + totalrecord.ToString() + ",\"rows\":[";
            string str  = list.ToJSON().Replace("\n", " ").Replace("\r", " ").Replace("null","").Replace("[BR]"," ").Replace("@@@@"," ").Replace("@@"," ");
            strFormat = strFormat + str + "]};";
            //strFormat = strFormat.Replace(new Regex("(^|[^\\\\])\\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\\"","$1new Date($2)");
            if (strType =="1")
            {
                HttpContext.Current.Response.Write("[" + str.Replace("null","").Replace("[A]","&") + "]");
            }
            else
            {
                HttpContext.Current.Response.Write(strFormat);
            }
            //iSunContext.Current.Context.Response.Write("["+str+"]");
        }

        /// <summary>
        /// 获取角色数据权限信息
        /// </summary>
        /// <returns></returns>
        public string getRoleCondition()
        {
            IList<ZX.EHR.Library.SysRoleFunction> list = (new ZX.BLL.BUser()).GetRoleFunction(this.UserId, this.FunctionID);
            StringBuilder strCondition = new StringBuilder("");
            
            if (list == null)
            {
                return "";
            }
            foreach (var entity in list)
            {
                switch (entity.OperateRangeType.Trim())
                {
                    ///只能查看本人数据
                    case "0":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        strCondition.Append(string.Format(" AddUser='{0}'", this.UserId));
                        break;
                    ///可以看本部门的
                    case "1":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        strCondition.Append(string.Format(" AddUser in (select * from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        break;
                    // 全部数据
                    case "2":
                        break;
                    // 自定义条件数据
                    case "3":
                        //strCondition.Append(string.Format(" AddUser in (select * from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        break;
                    case "4":
                        break;
                    default:
                        break;
                }
            }

            //只用客户用户时使用
            if (this.User.IsOutsite == true)
            {
                if (this.EntityName == "TrActivity")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }

                    strCondition.Append(string.Format("(TrCustomerID='{0}')", User.CustomerID));

                }
                if (this.EntityName == "V_TrActivityCourse")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }

                    strCondition.Append(string.Format("(TrCustomerID = '{0}')", User.CustomerID));
               }

               
            }
            if (this.EntityName == "V_TrStudyGain")
            {
                if (strCondition.ToString() != "")
                {
                    strCondition.Append(" OR ");
                }

                strCondition.Append(string.Format("(PrincipalHrmanno = '{0}')", this.UserId));
            }

            return string.IsNullOrEmpty(strCondition.ToString())?"": "("+ strCondition.ToString()+")";
            //this.UserId
        }

    }
}
